<template>
  <div class="flex h-screen w-full bg-[#fafbfc]">
    <div class="relative flex-1">
      <router-link to="/">
        <div class="absolute top-10 left-10 mb-[9px] flex items-center justify-center">
          <img
            src="@/assets/images/logo.png"
            alt="logo"
            class="h-[41px] w-auto"
          />
          <div class="ml-[9px] font-['抖音美好体'] text-[22px] text-white">星绘</div>
        </div>
      </router-link>
      <img
        src="@/assets/images/loginLeftBg.png"
        alt=""
        class="h-screen w-full object-cover"
      />
    </div>
    <div class="relative flex-1">
      <div
        class="absolute top-[34%] left-1/2 mx-auto -mt-[90px] w-4/5 max-w-[500px] -translate-x-1/2 rounded-xl bg-white px-[50px] py-[50px] shadow-[0_0_1px_rgba(0,0,0,0.2),0_0_4px_rgba(0,0,0,0.02),0_12px_36px_rgba(0,0,0,0.06)]"
      >
        <h1 class="mb-[1px] text-center text-[22px] text-black">
          <img
            src="@/assets/images/logo.png"
            alt="logo"
            class="mr-[9px] inline-block h-[29px]"
          />零代码应用生成平台
        </h1>
        <div class="mb-[25px] text-center text-[14px] font-medium text-[#888]">
          让每个人都具备程序员能力
        </div>
        <a-form
          :model="formState"
          layout="vertical"
          name="basic"
          autocomplete="off"
          @finish="onFinish"
        >
          <a-form-item class="!mb-[13px] last:mb-0">
            <div class="mb-[9px] ml-[-14px] flex justify-center">
              <div
                class="relative mx-[14px] cursor-pointer px-[4px] pb-[3px] text-[15px] transition-colors duration-[400ms] ease-in-out"
                :class="
                  formTypeIndex === 0
                    ? 'font-medium text-[#4f65f9]'
                    : 'text-black hover:text-[#4f65f9]'
                "
                @click="switchFormType(0)"
              >
                <span class="relative z-[2]">登录</span>
                <div
                  class="absolute bottom-0 left-1/2 h-1 -translate-x-1/2 rounded-[5px] bg-[#4f65f9] transition-all duration-[400ms] ease-in-out"
                  :class="
                    formTypeIndex === 0 ? 'visible w-full opacity-100' : 'invisible w-0 opacity-0'
                  "
                ></div>
              </div>
              <div
                class="relative mx-[14px] cursor-pointer px-[4px] pb-[3px] text-[15px] transition-colors duration-[400ms] ease-in-out"
                :class="
                  formTypeIndex === 1
                    ? 'font-medium text-[#4f65f9]'
                    : 'text-black hover:text-[#4f65f9]'
                "
                @click="switchFormType(1)"
              >
                <span class="relative z-[2]">注册</span>
                <div
                  class="absolute bottom-0 left-1/2 h-1 -translate-x-1/2 rounded-[5px] bg-[#4f65f9] transition-all duration-[400ms] ease-in-out"
                  :class="
                    formTypeIndex === 1 ? 'visible w-full opacity-100' : 'invisible w-0 opacity-0'
                  "
                ></div>
              </div>
            </div>
          </a-form-item>
          <a-form-item
            class="!mb-[15px] last:mb-0"
            name="username"
            :rules="[{ required: true, message: '请输入用户名~' }]"
          >
            <a-input
              class="h-10 text-[13px]"
              v-model:value="formState.username"
              placeholder="请输入用户名~"
            >
              <template #prefix>
                <UserOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item
            class="!mb-[15px]"
            name="password"
            :rules="[{ required: true, message: '请输入密码~' }]"
          >
            <a-input-password
              class="h-10 text-[13px]"
              v-model:value="formState.password"
              placeholder="请输入密码~"
            >
              <template #prefix> <ExclamationCircleOutlined /></template>
            </a-input-password>
          </a-form-item>

          <a-form-item
            class="!mb-[20px] text-right last:mb-0"
            v-if="formTypeActive === 'login'"
          >
            <a-checkbox
              v-model:checked="formState.isRemember"
              @change="handleRememberChange"
            >
              <p class="mb-0 text-[13px] leading-[1.2] text-[#666]">记住密码</p>
            </a-checkbox>
          </a-form-item>

          <a-form-item
            class="!mb-[15px] last:mb-0"
            name="passwordConfirm"
            :rules="[{ required: true, message: '请再次输入密码~' }]"
            v-if="formTypeActive === 'register'"
          >
            <a-input-password
              class="h-10 text-[13px]"
              v-model:value="formState.passwordConfirm"
              placeholder="请再次输入密码~"
            >
              <template #prefix> <ExclamationCircleOutlined /></template>
            </a-input-password>
          </a-form-item>

          <a-form-item
            class="!mb-[20px] last:mb-0"
            v-if="formTypeActive === 'register'"
          >
            <a-checkbox v-model:checked="formState.isAgreement">
              <p class="mb-0 text-[13px] leading-[1.2] text-[#666]">
                注册即代表已阅读并同意我们的<router-link
                  to="/user/agreement"
                  class="text-[#4f65f9]"
                  >用户协议</router-link
                >和<router-link
                  to="/user/policy"
                  class="text-[#4f65f9]"
                  >隐私政策</router-link
                >
              </p>
            </a-checkbox>
          </a-form-item>

          <a-form-item class="!mb-[0px] text-center">
            <a-button
              class="!h-[40px]"
              block
              type="primary"
              html-type="submit"
              :loading="isBtnLoading"
            >
              {{ formTypeActive === 'login' ? '登录' : '注册' }}
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { UserOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { userLogin, userRegister } from '@/api/userController';
import { useUserStore } from '@/stores/user';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';

// 表单数据类型
interface FormState {
  username: string;
  password: string;
  passwordConfirm: string;
  isAgreement: boolean;
  isRemember: boolean;
}

// 用户store
const userStore = useUserStore();
const router = useRouter();

// 表单数据
const formState = reactive<FormState>({
  // 用户名(登录/注册)
  username: '',
  // 密码(登录/注册)
  password: '',
  // 确认密码(注册)
  passwordConfirm: '',
  // 是否同意隐私政策(注册)
  isAgreement: false,
  // 是否记住密码(登录)
  isRemember: false
});

// 初始化表单数据（从 store 恢复记住的用户信息）
const initFormState = () => {
  const rememberedInfo = userStore.getRememberedInfo();
  if (rememberedInfo.isRemember) {
    formState.username = rememberedInfo.username;
    formState.password = rememberedInfo.password;
    formState.isRemember = rememberedInfo.isRemember;
  } else {
    // 如果没有记住密码，清空表单
    formState.username = '';
    formState.password = '';
    formState.isRemember = false;
  }
};

// 组件挂载时初始化表单
onMounted(() => {
  initFormState();
});

// 表单类型
const formTypeList = reactive(['login', 'register']);
// 表单类型索引
const formTypeIndex = ref(0);

/**
 * 映射当前状态(登录/注册)
 */
const formTypeActive = computed(() => {
  return formTypeList[formTypeIndex.value];
});

// 按钮状态
const isBtnLoading = ref<boolean>(false);

/**
 * 提交表单事件
 * @param values 表单数据
 */
const onFinish = async () => {
  // 登录
  if (formTypeActive.value === 'login') {
    try {
      isBtnLoading.value = true;
      const userInfo = {
        userAccount: formState.username,
        userPassword: formState.password
      };
      const res = await userLogin(userInfo as API.UserLoginRequest);
      if (res.data?.code === 0 && res.data.data) {
        // 登录成功后保存或清除记住的用户信息
        userStore.saveRememberedInfo(formState.username, formState.password, formState.isRemember);
        userStore.setLoginUser(res.data.data as API.LoginUserVO);
        message.success('登录成功');
        router.push('/');
      } else {
        message.error(res.data?.message || '登录失败');
      }
    } catch (error) {
      console.error(error);
      message.error('登录失败');
    } finally {
      isBtnLoading.value = false;
    }
  }

  // 注册
  if (formTypeActive.value === 'register') {
    try {
      isBtnLoading.value = true;
      if (formState.password !== formState.passwordConfirm) {
        message.error('密码不一致');
        isBtnLoading.value = false;
        return;
      }
      if (!formState.isAgreement) {
        message.error('请同意用户协议和隐私政策');
        isBtnLoading.value = false;
        return;
      }
      const res = await userRegister({
        userAccount: formState.username,
        userPassword: formState.password,
        checkPassword: formState.passwordConfirm
      });
      if (res.data?.code === 0 && res.data.data) {
        message.success('注册成功');
        // 注册成功后切换到登录表单，并清空表单
        formTypeIndex.value = 0;
        formState.passwordConfirm = '';
        formState.isAgreement = false;
        // 恢复记住的用户信息
        initFormState();
      } else {
        message.error(res.data?.message || '注册失败');
      }
    } catch (error) {
      console.error(error);
      message.error('注册失败');
    } finally {
      isBtnLoading.value = false;
    }
  }
};

/**
 * 处理记住密码状态变化
 */
const handleRememberChange = () => {
  // 如果取消记住密码，立即清除已保存的信息
  if (!formState.isRemember) {
    userStore.clearRememberedInfo();
  }
};

/**
 * 切换按钮类型
 * @param index 按钮索引
 */
const switchFormType = (index: number) => {
  formTypeIndex.value = index;

  if (index === 0) {
    // 切换到登录表单时，恢复记住的用户信息
    initFormState();
  } else {
    // 切换到注册表单时，清空表单
    formState.username = '';
    formState.password = '';
    formState.isRemember = false;
  }

  formState.passwordConfirm = '';
  formState.isAgreement = false;
};
</script>
